<template>
  <div class="check-input-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Edit /></el-icon>
          <div class="header-text">
            <h2>盘点数据录入</h2>
            <p>录入商品实盘数量</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
          <el-button type="success" @click="handleSave" :loading="saving">
            <el-icon><Select /></el-icon>
            保存
          </el-button>
          <el-button type="primary" @click="handleComplete" :loading="saving">
            <el-icon><CircleCheck /></el-icon>
            完成盘点
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 盘点单信息 -->
    <el-card shadow="never" class="info-card">
      <el-descriptions :column="4" border>
        <el-descriptions-item label="盘点单号">{{ sheetInfo.sheetNo }}</el-descriptions-item>
        <el-descriptions-item label="关联任务">{{ sheetInfo.taskNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="盘点仓库">{{ sheetInfo.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="盘点人">{{ sheetInfo.checkPerson }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 盘点进度 -->
    <el-card shadow="never" class="progress-card">
      <div class="progress-header">
        <span class="progress-title">盘点进度</span>
        <span class="progress-stats">
          已盘：<span class="checked-count">{{ checkedCount }}</span> / 
          总计：<span class="total-count">{{ totalCount }}</span>
        </span>
      </div>
      <el-progress 
        :percentage="progressPercentage" 
        :stroke-width="20"
        :status="progressPercentage === 100 ? 'success' : ''"
      >
        <span class="progress-text">{{ progressPercentage }}%</span>
      </el-progress>
    </el-card>

    <!-- 快速筛选 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="商品搜索">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="商品编码/名称" 
            clearable 
            style="width: 300px"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态筛选">
          <el-radio-group v-model="searchForm.status" @change="handleSearch">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="unchecked">未盘点</el-radio-button>
            <el-radio-button label="checked">已盘点</el-radio-button>
            <el-radio-button label="diff">有差异</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleBatchInput">
            <el-icon><Edit /></el-icon>
            批量录入
          </el-button>
          <el-button @click="handleImport">
            <el-icon><Upload /></el-icon>
            导入数据
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 盘点明细表格 -->
    <el-card shadow="never">
      <el-table 
        :data="filteredItems" 
        border 
        stripe
        :row-class-name="getRowClassName"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" fixed />
        <el-table-column prop="productCode" label="商品编码" width="150" fixed>
          <template #default="{ row }">
            <div class="product-code">
              <el-icon v-if="row.checked" color="#67C23A"><CircleCheckFilled /></el-icon>
              <el-icon v-else color="#E6A23C"><Warning /></el-icon>
              {{ row.productCode }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="spec" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="bookQty" label="账面数量" width="120" align="right">
          <template #default="{ row }">
            <span class="book-qty">{{ row.bookQty }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实盘数量" width="180" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.actualQty"
              :min="0"
              :precision="2"
              :step="1"
              controls-position="right"
              @change="handleQtyChange(row)"
              style="width: 160px"
            />
          </template>
        </el-table-column>
        <el-table-column label="盈亏数量" width="120" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.diffQty)">
              {{ row.diffQty > 0 ? '+' : '' }}{{ row.diffQty }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.unitPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="盈亏金额" width="150" align="right">
          <template #default="{ row }">
            <span :class="getDiffClass(row.diffAmount)" class="diff-amount">
              {{ row.diffAmount > 0 ? '+' : '' }}¥{{ Math.abs(row.diffAmount).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="200">
          <template #default="{ row }">
            <el-input
              v-model="row.remark"
              placeholder="填写盈亏原因"
              clearable
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button 
              link 
              type="success" 
              @click="handleQuickCheck(row)" 
              size="small"
              v-if="!row.checked"
            >
              <el-icon><Select /></el-icon>
              确认
            </el-button>
            <el-button 
              link 
              type="warning" 
              @click="handleRecheck(row)" 
              size="small"
              v-else
            >
              <el-icon><RefreshRight /></el-icon>
              重新盘点
            </el-button>
            <el-button 
              link 
              type="primary" 
              @click="handleViewHistory(row)" 
              size="small"
            >
              <el-icon><Clock /></el-icon>
              历史
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <div class="footer-summary">
          <span class="summary-item">
            <strong>盈亏汇总：</strong>
            总盈亏数量：
            <span :class="getDiffClass(totalDiffQty)">
              {{ totalDiffQty > 0 ? '+' : '' }}{{ totalDiffQty }}
            </span>
            ，总盈亏金额：
            <span :class="getDiffClass(totalDiffAmount)" class="total-amount">
              {{ totalDiffAmount > 0 ? '+' : '' }}¥{{ Math.abs(totalDiffAmount).toFixed(2) }}
            </span>
          </span>
        </div>
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 批量录入对话框 -->
    <el-dialog v-model="showBatchDialog" title="批量录入" width="500px">
      <el-form :model="batchForm" label-width="120px">
        <el-form-item label="操作类型">
          <el-radio-group v-model="batchForm.type">
            <el-radio label="same">账实相符</el-radio>
            <el-radio label="custom">自定义数量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="实盘数量" v-if="batchForm.type === 'custom'">
          <el-input-number v-model="batchForm.qty" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="应用范围">
          <el-radio-group v-model="batchForm.scope">
            <el-radio label="all">全部商品</el-radio>
            <el-radio label="unchecked">未盘点商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="统一备注">
          <el-input v-model="batchForm.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchDialog = false">取消</el-button>
        <el-button type="primary" @click="handleBatchConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 历史记录对话框 -->
    <el-dialog v-model="showHistoryDialog" title="盘点历史" width="800px">
      <el-timeline>
        <el-timeline-item
          v-for="(record, index) in historyRecords"
          :key="index"
          :timestamp="record.time"
          placement="top"
          :type="record.type"
        >
          <el-card>
            <h4>{{ record.title }}</h4>
            <p>{{ record.desc }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-if="historyRecords.length === 0" description="暂无历史记录" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Edit, Back, Select, CircleCheck, Search, Upload, CircleCheckFilled,
  Warning, RefreshRight, Clock
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 状态
const saving = ref(false)
const showBatchDialog = ref(false)
const showHistoryDialog = ref(false)

// 盘点单信息
const sheetInfo = reactive({
  id: route.query.id || 1,
  sheetNo: 'CHS202401150001',
  taskNo: 'CHK202401150001',
  warehouseId: 1,
  warehouseName: '主仓库',
  checkPerson: '张三'
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: 'all'
})

// 批量录入表单
const batchForm = reactive({
  type: 'same',
  qty: 0,
  scope: 'unchecked',
  remark: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 盘点明细数据
const checkItems = ref([
  {
    id: 1,
    productCode: 'P001',
    productName: 'iPhone 15 Pro Max 256GB',
    spec: '256GB 深空黑',
    unit: '台',
    bookQty: 100,
    actualQty: null,
    diffQty: 0,
    unitPrice: 9999,
    diffAmount: 0,
    remark: '',
    checked: false
  },
  {
    id: 2,
    productCode: 'P002',
    productName: 'MacBook Pro 14寸 M3',
    spec: '14寸 16GB 512GB',
    unit: '台',
    bookQty: 50,
    actualQty: null,
    diffQty: 0,
    unitPrice: 14999,
    diffAmount: 0,
    remark: '',
    checked: false
  },
  {
    id: 3,
    productCode: 'P003',
    productName: 'AirPods Pro 2',
    spec: '第二代',
    unit: '副',
    bookQty: 200,
    actualQty: null,
    diffQty: 0,
    unitPrice: 1899,
    diffAmount: 0,
    remark: '',
    checked: false
  },
  {
    id: 4,
    productCode: 'P004',
    productName: 'iPad Air 5',
    spec: '10.9寸 WiFi 64GB',
    unit: '台',
    bookQty: 80,
    actualQty: null,
    diffQty: 0,
    unitPrice: 4799,
    diffAmount: 0,
    remark: '',
    checked: false
  },
  {
    id: 5,
    productCode: 'P005',
    productName: 'Apple Watch Series 9',
    spec: '45mm GPS',
    unit: '块',
    bookQty: 60,
    actualQty: null,
    diffQty: 0,
    unitPrice: 3199,
    diffAmount: 0,
    remark: '',
    checked: false
  }
])

// 历史记录
const historyRecords = ref([])

// 计算属性
const filteredItems = computed(() => {
  let result = checkItems.value

  // 关键词搜索
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    result = result.filter(item =>
      item.productCode.toLowerCase().includes(keyword) ||
      item.productName.toLowerCase().includes(keyword)
    )
  }

  // 状态筛选
  if (searchForm.status === 'unchecked') {
    result = result.filter(item => !item.checked)
  } else if (searchForm.status === 'checked') {
    result = result.filter(item => item.checked)
  } else if (searchForm.status === 'diff') {
    result = result.filter(item => item.diffQty !== 0)
  }

  pagination.total = result.length
  return result
})

const checkedCount = computed(() => {
  return checkItems.value.filter(item => item.checked).length
})

const totalCount = computed(() => {
  return checkItems.value.length
})

const progressPercentage = computed(() => {
  if (totalCount.value === 0) return 0
  return Math.round((checkedCount.value / totalCount.value) * 100)
})

const totalDiffQty = computed(() => {
  return checkItems.value.reduce((sum, item) => sum + item.diffQty, 0)
})

const totalDiffAmount = computed(() => {
  return checkItems.value.reduce((sum, item) => sum + item.diffAmount, 0)
})

// 方法
const handleQtyChange = (row) => {
  if (row.actualQty !== null) {
    row.diffQty = row.actualQty - row.bookQty
    row.diffAmount = row.diffQty * row.unitPrice
    row.checked = true
  } else {
    row.diffQty = 0
    row.diffAmount = 0
    row.checked = false
  }
}

const handleQuickCheck = (row) => {
  if (row.actualQty === null) {
    ElMessage.warning('请先输入实盘数量')
    return
  }
  row.checked = true
  ElMessage.success('确认成功')
}

const handleRecheck = (row) => {
  row.checked = false
  ElMessage.info('已标记为重新盘点')
}

const handleSearch = () => {
  pagination.page = 1
}

const handlePageChange = () => {
  console.log('分页变化', pagination)
}

const handleBatchInput = () => {
  showBatchDialog.value = true
}

const handleBatchConfirm = () => {
  let targetItems = checkItems.value
  
  if (batchForm.scope === 'unchecked') {
    targetItems = checkItems.value.filter(item => !item.checked)
  }
  
  targetItems.forEach(item => {
    if (batchForm.type === 'same') {
      item.actualQty = item.bookQty
    } else {
      item.actualQty = batchForm.qty
    }
    handleQtyChange(item)
    if (batchForm.remark) {
      item.remark = batchForm.remark
    }
  })
  
  showBatchDialog.value = false
  ElMessage.success(`已批量录入${targetItems.length}条数据`)
}

const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

const handleViewHistory = (row) => {
  historyRecords.value = [
    {
      time: '2024-01-15 14:30:00',
      type: 'primary',
      title: '首次盘点',
      desc: `账面数量：${row.bookQty}，实盘数量：${row.actualQty || '-'}，盘点人：张三`
    }
  ]
  showHistoryDialog.value = true
}

const handleSave = () => {
  saving.value = true
  setTimeout(() => {
    saving.value = false
    ElMessage.success('保存成功')
  }, 1000)
}

const handleComplete = () => {
  const uncheckedCount = checkItems.value.filter(item => !item.checked).length
  
  if (uncheckedCount > 0) {
    ElMessageBox.confirm(
      `还有${uncheckedCount}个商品未盘点，确定要完成盘点吗？`,
      '提示',
      {
        type: 'warning',
        confirmButtonText: '确定完成',
        cancelButtonText: '继续盘点'
      }
    ).then(() => {
      completeCheck()
    }).catch(() => {})
  } else {
    completeCheck()
  }
}

const completeCheck = () => {
  saving.value = true
  setTimeout(() => {
    saving.value = false
    ElMessage.success('盘点完成')
    router.push('/inventory/check-sheets')
  }, 1000)
}

const handleBack = () => {
  router.back()
}

const getRowClassName = ({ row }) => {
  if (row.checked && row.diffQty !== 0) {
    return 'row-has-diff'
  }
  if (!row.checked) {
    return 'row-unchecked'
  }
  return ''
}

const getDiffClass = (value) => {
  if (value > 0) return 'profit-text'
  if (value < 0) return 'loss-text'
  return ''
}

// 生命周期
onMounted(() => {
  pagination.total = checkItems.value.length
})
</script>

<style scoped>
.check-input-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.info-card,
.progress-card,
.filter-card {
  margin-bottom: 20px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.progress-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.progress-stats {
  font-size: 14px;
  color: #606266;
}

.checked-count {
  color: #67C23A;
  font-weight: 600;
  font-size: 18px;
}

.total-count {
  color: #409EFF;
  font-weight: 600;
  font-size: 18px;
}

.progress-text {
  font-size: 14px;
  font-weight: 500;
}

.product-code {
  display: flex;
  align-items: center;
  gap: 6px;
}

.book-qty {
  color: #606266;
  font-weight: 500;
}

.diff-amount {
  font-weight: 600;
  font-size: 14px;
}

.profit-text {
  color: #67C23A;
  font-weight: 500;
}

.loss-text {
  color: #F56C6C;
  font-weight: 500;
}

.table-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-summary {
  font-size: 14px;
  color: #606266;
}

.summary-item strong {
  margin-right: 8px;
}

.total-amount {
  font-size: 16px;
  font-weight: 600;
}

/* 行样式 */
:deep(.row-unchecked) {
  background-color: #fef0e6 !important;
}

:deep(.row-has-diff) {
  background-color: #e6f7ff !important;
}

:deep(.el-table__row:hover > td) {
  background-color: #f5f7fa !important;
}
</style>

